import Vue from 'vue'
import VueRouter from 'vue-router'
import {
  Message
} from 'element-ui'

Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  },
  // 登录页
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login')
  },
  // 主页
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home'),
    redirect: '/welcome',
    children: [{
        path: '/welcome',
        name: 'Welcome',
        component: () => import('@/views/Welcome')
      },
      {
        path: '/users',
        name: 'User',
        component: () => import('@/views/user/User')
      },
      {
        path: '/rights',
        name: 'Rights',
        component: () => import('@/views/power/Rights')
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('@/views/power/Roles')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行  next('/login') 强制跳转
  if (to.path === '/login') {
    return next()
  }
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    Message.error('登录超时，请重新登录')
    return next('/login')
  }
  // 放行
  next()
})

export default router
